# -*- coding: utf-8 -*-

import re, os
from datetime import date

from django.shortcuts import render_to_response

from django.template import RequestContext

from django.core.exceptions import ValidationError

from django.conf import settings

from django.contrib.auth.models import Group

from django.utils import version

birth_date_matcher = re.compile(r'[0-3][0-9][0-1][0-9]\d{4}0{5}')
rev_cache = None

def render_to(template_name):
  def renderer(func):
    def wrapper(request, *args, **kw):
      output = func(request, *args, **kw)
      if not isinstance(output, dict):
        return output
      # Add revision number
      output['revision'] = revision()
      return render_to_response(template_name, output, RequestContext(request))
    return wrapper
  return renderer

def check_emso(emso):
  """Checks the corectness of EMSO number.
  """
  # It needs to be exacetly 13
  if len(emso) != 13:
    raise ValidationError(u"EMŠO '%s' ni pravilne dolžine (13)" % emso)
  
  # It needs to be only numeric
  if emso.isdigit() is False:
    raise ValidationError(u"EMŠO '%s' mora biti sestavljen le it števk" % emso)
  
  # If it is just a birth date, then don't calculate control digit
  if birth_date_matcher.match(emso) is None:
    # Calculate the control digit
    weights = [7, 6, 5, 4, 3, 2, 7, 6, 5, 4, 3, 2]
    digits = [int(digit) for digit in emso]
    control = sum([weights[i] * digits[i] for i in xrange(0, len(weights))]) % 11
    control = 11 - control if control > 0 else 0
    
    # Check the calculated control digit and the lash digit
    if control != digits[-1]:
      raise ValidationError(u"Kontrolna števka v '%s' se ne ujema z izračunano števko" % emso)
  else:
    # A date check :)
    try:
      date(int(emso[4:4+4]), int(emso[2:2+2]), int(emso[0:2]))
    except:
      raise ValidationError(u"Napačen datum")

def get_group(name):
  return Group.objects.get(pk = settings.GROUPS[name])
  
def get_display(choices, val):
  for c,text in choices:
    if c == val:
      return text
  return None

def revision():
  global rev_cache
  
  if rev_cache:
    return rev_cache
  
  revisions = []
  for path in (d + '/' + j for d, i, _ in os.walk(settings.ROOT_DIR) if '.svn' not in d and d is not [] and i != ['.svn'] for j in i if j != '.svn'):
    try:
      revisions.append(int(version.get_svn_revision(path).replace('SVN-', '')))
    except:
      pass
  rev_cache = max(revisions)
  return rev_cache
  
